<?php

	require_once dirname(__FILE__) . '/Connection.php';
	
	class ProfessorPDO
	{

		private $connection = null;
		
		public function __construct()
		{
			$this->connection = Connection::getInstance();
		}
		
		public function inserir($professor)
		{
			try {
				$this->connection->beginTransaction();
				$stmt = $this->connection->prepare("INSERT INTO usuario
													(username, password, perfil)
													VALUES (:username, :password, :perfil);");
				$stmt->bindValue('username', $professor->usuario->username);
				$stmt->bindValue('password', $professor->usuario->password);
				$stmt->bindValue('perfil', $professor->usuario->perfil);
				$stmt->execute();
				$stmt = $this->connection->query("SELECT LAST_INSERT_ID() INTO @ID;");
				$stmt->execute();
				$stmt = $this->connection->prepare("INSERT INTO professor
													(nome, email, cpf, usuario_id)
													VALUES (:nome, :email, :cpf, @ID);");
				$stmt->bindValue('nome', $professor->nome);
				$stmt->bindValue('email', $professor->email);
				$stmt->bindValue('cpf', $professor->cpf);
				$stmt->execute();
				$this->connection->commit();
			}
			catch(Exception $erro){
				echo $erro->getMessage();
				$this->connection->rollback();
			}
		}
		
		public function alterar($professor)
		{
			try {
				$this->connection->beginTransaction();
				$stmt = $this->connection->prepare("UPDATE professor
													SET nome=:nome, email:email, cpf:cpf WHERE id=:id");
				$stmt->bindValue('nome', $professor->nome);
				$stmt->bindValue('nome', $professor->email);
				$stmt->bindValue('nome', $professor->cpf);
				$stmt->bindValue('id', $professor->id);
				$stmt->execute();
				$this->connection->commit();
			}
			catch(Exception $erro){
				$this->connection->rollback();
			}
		}
		
		public function deletar($id)
		{
			try {
				$this->connection->beginTransaction();
				$stmt = $this->connection->prepare("DELETE FROM professor WHERE id=:id");
				$stmt->bindValue('id', $id);
				$stmt->execute();
				$this->connection->commit();
			}
			catch(Exception $erro){
				$this->connection->rollback();
			}
		}
		
		public function pesquisar($busca)
		{
			$consulta = $this->connection->prepare("SELECT * FROM professor p
												  INNER JOIN usuario u ON p.usuario_id=u.id
												  WHERE p.nome LIKE :busca ORDER BY p.nome;");
			$consulta->bindValue('busca', ('%'.$busca.'%'));
			$consulta->execute();
			return  $consulta->fetchAll(PDO::FETCH_ASSOC);
		}
		
		public function listar()
		{
			$lista = Array();
			$consulta = $this->connection->query("SELECT * FROM professor p
												  INNER JOIN usuario u ON p.usuario_id=u.id
												  ORDER BY p.nome;");
			$consulta->execute();
			return $consulta->fetchAll(PDO::FETCH_ASSOC);			
		}
	}
?>